﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using SharpDX;
using SharpDX.XAPO;
using SynergyLib.DSP;
using SynergyLib.SMath;

namespace XAudio2Controls
{
    [StructLayout(LayoutKind.Sequential)]
    public struct RingModulationParams
    {
        internal float ModFreq { get; set; }
        internal float RingFreq { get; set; }
    }

    public class RingModulationEffect : AudioProcessorBase<RingModulationParams>
    {
        public RingModulationEffect()
        {
            RegistrationProperties = new RegistrationProperties()
            {
                Clsid = Utilities.GetGuidFromType(typeof(RingModulationEffect)),
                CopyrightInfo = "Copyright",
                FriendlyName = "RingModulation",
                MaxInputBufferCount = 100,
                MaxOutputBufferCount = 100,
                MinInputBufferCount = 100,
                MinOutputBufferCount = 100,
                Flags = PropertyFlags.Default
            };
        }

        public override void Process(BufferParameters[] inputProcessParameters, BufferParameters[] outputProcessParameters, bool isEnabled)
        {
            int frameCount = inputProcessParameters[0].ValidFrameCount;
            DataStream input = new DataStream(inputProcessParameters[0].Buffer, frameCount * InputFormatLocked.BlockAlign, true, true);
            DataStream Output = new DataStream(inputProcessParameters[0].Buffer, frameCount * InputFormatLocked.BlockAlign, true, true);
            for (int i = 0; i < frameCount; i++, Counter++)
            {
                float left = input.Read<float>();
                float right = input.Read<float>();

                //float Fc = 440f;
                float carrier = (float)Math.Sin(Trig.TwoPI * i * Parameters.ModFreq / Fs);

                //float Fx = 220f;
                float modulator = (float)Math.Sin(Trig.TwoPI * i * Parameters.RingFreq / Fs);

                Output.Write(left * carrier * modulator);
                Output.Write(right * carrier * modulator);
            }
        }

    }
}
